import 'dart:convert';

import 'package:PollOnLine/ui/home/complete_poll/complete_poll_view.dart';
import 'package:PollOnLine/ui/home/task_detail/task_detail_logic.dart';
import 'package:PollOnLine/utils/EventBusUtils.dart';
import 'package:PollOnLine/utils/logger_utils.dart';
import 'package:PollOnLine/utils/path_provider_utils.dart';
import 'package:PollOnLine/utils/path_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:record/record.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../../bean/FileRes.dart';
import '../../../utils/amap_utils.dart';
import '../../../utils/timer_utils.dart';
import '../../../utils/url_launcher_utils.dart';
import '../../../utils/utils.dart';
import '../complete_poll/complete_poll_view_ipad.dart';
import 'add_poll_state.dart';

class AddPollLogic extends GetxController {
  final AddPollState state = AddPollState();

  late WebViewController wbController = WebViewController();

  late AudioRecorder record = AudioRecorder();

  // busType "1-1"是录音  "1-2"签名  '1-3'图片视频

  late String writeId; // 问卷ID

  late TaskDetailLogic taskDetailLogic = Get.find<TaskDetailLogic>();

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments.isNotEmpty) {
      state.url = Get.arguments;
      kLog.i(state.url);
    }
    state.isPosition = taskDetailLogic.state.isPosition;
    state.isRecord = taskDetailLogic.state.isRecord;
    initWebViewController();
  }

  void initWebViewController() {
    wbController.setJavaScriptMode(JavaScriptMode.unrestricted);
    wbController.setNavigationDelegate(NavigationDelegate(
      onNavigationRequest: (NavigationRequest request) async {
        // 处理android net::ERR_UNKNOWN_URL_SCHEME 问题
        if (request.url.startsWith("http://") || request.url.startsWith("https://")) {
          return NavigationDecision.navigate;
        } else {
          await UrlLauncherUtils().launchs(request.url);
          return NavigationDecision.prevent;
        }
      },
      onProgress: (int progress) {},
      onPageFinished: (String url) {
        if (state.isRecord) {
          initAudioRecorder();
        }
      },
      onWebResourceError: (WebResourceError error) {
        kLog.e("errorCode:${error.errorCode}, description:${error.description}");
        if (state.isRecord) {
          disposeRecorder();
        }
      },
      onUrlChange: (UrlChange change) {},
    ));
    wbController.addJavaScriptChannel(
      "Toaster",
      onMessageReceived: (JavaScriptMessage message) {
        ScaffoldMessenger.of(Get.context!).showSnackBar(SnackBar(content: Text(message.message)));
      },
    );

    wbController.addJavaScriptChannel(
      "onQueSubmit",
      onMessageReceived: (JavaScriptMessage message) async {
        // 获取 作答问卷id
        writeId = jsonDecode(message.message)['writeId'];
        if (state.isRecord) {
          // 停止录音 开始上传文件
          stopRecorder(writeId);
        } else {
          bool b = await taskDetailLogic.saveTaskFile(writeId, location: state.location);
          nextStep(b);
        }
      },
    );
    wbController.loadRequest(Uri.parse(state.url));
    // wbController.loadFlutterAsset(state.url);
  }

  void runShowMessage(data) {
    wbController.runJavaScript('showMessage(${jsonEncode(data)})');
  }

  @override
  void onReady() {
    super.onReady();
    if (state.isPosition) {
      startLocation();
    }
  }

  // 初始化 开始 录音
  void initAudioRecorder() async {
    if (await record.hasPermission()) {
      // 开始计时
      startTimer();
      String path = '${await PathProviderUtils().getTempDir()}/audio_${DateTime.now().millisecondsSinceEpoch}.wav';
      const encoder = AudioEncoder.wav;
      const config = RecordConfig(encoder: encoder, numChannels: 1);
      await record.start(config, path: path);
    }
  }

  // 停止录音
  Future<void> stopRecorder(String writeId) async {
    TimerUtils().pause();
    // /data/user/0/com.topnet.pollonline/app_flutter/audio_1704963601169.mp3
    final path = await record.stop();
    if (path != null) {
      String newPath = '${await PathProviderUtils().getTempDir()}/$writeId.wav';
      PathUtils.rename(path, newPath);
      FileRes? fileRes = await taskDetailLogic.uploadFile(newPath);
      bool b = await taskDetailLogic.saveTaskFile(writeId, fileRes: fileRes, location: state.location);
      nextStep(b);
    }
  }

  // 文件保存成功后 进行下一步判断
  void nextStep(bool b) {
    if (b) {
      if (taskDetailLogic.state.isSignature || taskDetailLogic.state.isVideo) {
        // 跳转完成调研
        completePoll();
      } else {
        // 当 不需要签名和也不需要照片或视频时  直接调用完成接口
        taskDetailLogic.completeWrite(writeId);
      }
    }
  }

  // dispose销毁
  void disposeRecorder() {
    // 计时器销毁
    TimerUtils().cancel();
    // 录音销毁
    record.dispose();
  }

  // 开始记时
  void startTimer() {
    TimerUtils().start((String time) {
      state.time = time;
      update();
    });
  }

  // 获取位置信息
  void startLocation() async {
    state.location = await AMapUtils().startLocation();
    update();
  }

  // 跳转完成调研
  void completePoll() {
    bus.fire(TaskDetail());
    bus.fire(TaskList());
    Map<String, dynamic> params = {
      "writeId": writeId,
      "isSignature": taskDetailLogic.state.isSignature,
      "isVideo": taskDetailLogic.state.isVideo,
    };
    if (isPad(Get.context!)) {
      Get.off(() => const CompletePollPageIpad(title: '完成调研'), arguments: params);
    } else {
      Get.off(() => const CompletePollPage(title: '完成调研'), arguments: params);
    }
  }

  // void goto( ){
  //   Map<String, dynamic> params = {
  //     "writeId": "writeId",
  //     "isSignature": true,
  //     "isVideo": true,
  //   };
  //   Get.off(() => const CompletePollPageIpad(title: '完成调研'), arguments: params);
  // }

  @override
  void onClose() {
    super.onClose();
    // 销毁
    disposeRecorder();
  }
}
